package com.aiju.common;

import android.content.Context;
import android.util.Log;

import com.aiju.app.config.ConfigManager;
import com.aiju.utils.PreferencesUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;

/**
 * 全局处理异常.
 */
public class CrashHandler implements UncaughtExceptionHandler {
    /**
     * CrashHandler实例
     */

    private static CrashHandler instance;
    private Context mContext;
    private UncaughtExceptionHandler mDefaultHandler;

    /**
     * 获取CrashHandler实例 ,单例模式
     */

    public static CrashHandler getInstance() {
        if (instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread arg0, Throwable arg1) {
        String logdir = ConfigManager.getInstance().DIR_CACHE;

        File file = new File(logdir);
        boolean mkSuccess;
        if (!file.isDirectory()) {
            mkSuccess = file.mkdirs();
            if (!mkSuccess) {
                file.mkdirs();
            }
        }
        try {
            PreferencesUtils.putString(mContext, "password", "");
            FileWriter fw = new FileWriter(logdir + File.separator + "error.log", true);
            fw.write(new Date() + "\n");
            StackTraceElement[] stackTrace = arg1.getStackTrace();
            fw.write(arg1.getMessage() + "\n");
            for (int i = 0; i < stackTrace.length; i++) {
                fw.write("file:" + stackTrace[i].getFileName() + " class:" + stackTrace[i].getClassName()
                        + " method:" + stackTrace[i].getMethodName() + " line:" + stackTrace[i].getLineNumber()
                        + "\n");
            }
            fw.write("\n");
            fw.close();
        } catch (IOException e) {
            Log.e("crash handler", "load file failed...", e.getCause());
        }
        arg1.printStackTrace();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
